import { HttpException, HttpStatus, Injectable } from '@nestjs/common';
import { DataSource, Repository } from 'typeorm';
import { User } from './entities/user.entity';
import { InjectRepository } from '@nestjs/typeorm';
import JWT from 'src/utils/jwt';
import { Account } from './entities/account.entity';
import { UpdateUserDto } from './dto/update-user.dto';
import { RedisService } from 'src/redis/redis.service';

@Injectable()
export class UserService {
  constructor(
    @InjectRepository(User)
    private userRepository: Repository<User>,
    // private accountRepository: Repository<Account>,
    private dataSource: DataSource,
    private readonly redisService: RedisService
  ) {}
  /**
   * 
   * @param data 
   * @param session 
   * @returns 
   */
  async userLogin(data: any) {
    const queryRunner = this.dataSource.createQueryRunner()
    const result = await queryRunner
    .query(`SELECT * FROM user_tb u LEFT JOIN account_tb a ON u.user_id = a.user_id WHERE a.username = '${data.username}' and a.password = '${data.password}'`)
      if(result.length > 0) {
        const user: any = result[0];
        const token = JWT.generate({
          id: user.user_id,
          username: user.username,
        });
        // const redis = await this.redisService.getClient('root')
        this.redisService.setValue('token', token)
        this.redisService.setValue('userinfo', user)
        return {token, user}
      } else {
        return false;
      }
  }
  /**
   * 真删除
   * @param user_id 
   * @returns 
   */
  async delete(user_id: number) {
    const user: User = await this.userRepository
    .findOne({
      where: { user_id }
    })
    if(user) {
      const res = await this.userRepository.delete(user_id)
      return res;
    }
  }
  /**
   * 获取所有用户列表
   * @returns 
   */
  async userList(page: any): Promise<any> {
    try {
      const token = await this.redisService.getValue('token')
      const skip: number = (page.pageIndex-1) * page.pageSize;
      const take: number = page.pageSize;
      // const result = await this.userRepository.createQueryBuilder('u')
      // .leftJoinAndSelect('u.account', 'a', 'a.user_id = u.user_id')
      // .select(['u.*', 'a.username as username'])
      // .skip(skip)
      // .take(take)
      // .getMany() // 不能使用select指定字段列且只有主表数据
      // .getManyAndCount() // 虽然自带统计但是缺点和getMany()一样
      // .getRawMany() // 这个方法分页失效
      const total: number = await this.userRepository.createQueryBuilder('u')
      .leftJoinAndSelect('u.account', 'a', 'u.status = 1').getCount()
       const result: Array<User> = await this.userRepository
      .query(`
          SELECT u.*, a.username FROM user_tb u LEFT JOIN account_tb a
          ON u.user_id = a.user_id AND u.status = 1 LIMIT ${skip}, ${take}
      `)
      return {
        list: result, // 用户列表
        page: page.pageIndex, // 当前页码
        pageSize: result.length, // 查询条数
        next: page.pageIndex * page.pageSize < total, // 是否有下一页
        total: total, // 共多少条
        token: token,
      };
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_GATEWAY);
    }
  }
  /**
   * 获取用户信息
   * @param id 
   */
  async getUserInfo(id) {
    try {
      const result = await this.userRepository
      .query(`SELECT u.*, a.username FROM user_tb u LEFT JOIN account_tb a ON u.user_id = a.user_id WHERE u.user_id = '${id}'`)
      if(result.length > 0) {
        return result[0];
      } else {
        throw new HttpException('用户信息不存在', HttpStatus.BAD_GATEWAY);
      }
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_GATEWAY);
    }
  }
  /**
   * 新增用户
   * @param data 
   * @returns 
   */
  async addUser(data): Promise<any> {
    try {
      const setUser = new User()
      setUser.phone = data.phone
      setUser.avatar = data.avatar
      const user: User = await this.userRepository.manager.save(setUser)
      const setAccount = new Account()
      setAccount.user_id = user.user_id
      setAccount.username = data.username
      const account: Account = await this.dataSource.manager.save(setAccount);
      return Object.assign({ username: account.username }, user)
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_GATEWAY);
    }
  }
  // 修改用户信息
  async updateUser(data: UpdateUserDto) {
    try {
      let sql = `UPDATE user_tb u LEFT JOIN account_tb a ON a.user_id = u.user_id SET u.user_id=${data.user_id}`
    if(data.username) {
      sql += `, a.username='${data.username}'`
    }
    if(data.password) {
      sql += `, a.password='${data.password}'`
    }
    for(const [key, val] of Object.entries(data)) {
      if((key !== 'user_id') && (key !== 'username') && (key !=='password') && val) {
        sql +=`, u.${key}='${val}'`
      }
    }
    sql += `WHERE u.user_id = '${data.user_id}'`
    await this.userRepository.query(sql)
    return 'ok'
    } catch (error) {
      throw new HttpException(error.message, HttpStatus.BAD_GATEWAY);
    }
  }
}
